/*
  Author: Ionel Crisu - crisuionel@yahoo.com
  support@FlashExtended.com
*/
package com.flashextended.utils.server.filereference
{
	import flash.display.Bitmap;
	import flash.display.BitmapData;
	import flash.display.Loader;
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.FileFilter;
	import flash.net.FileReference;
	import flash.utils.ByteArray;
	
	import mx.controls.Alert;

	public class FileReferenceLocale extends FileReference
	{
		private static const IOERROR_MSG:String = "IOError at FileRef.as";
		private static const SECURITY_ERROR_MSG:String = "Security Error at FileRef.as";
		
		private var fileFilter:FileFilter;
		
		private var callBack:Function;
		
		public function FileReferenceLocale(fileFilter:FileFilter=null)
		{
			super();
			this.fileFilter = fileFilter;
			this.addEventListener(IOErrorEvent.IO_ERROR, ioErrorHandler);
			this.addEventListener(SecurityErrorEvent.SECURITY_ERROR, securityErrorHandler);
		}
		
		public function browseForDataLocally(callF:Function, isBytes:Boolean=false):void
		{
			callBack = callF;
			this.addEventListener(Event.SELECT, fileSelectedLocallyHandler);
			if(!isBytes)
			{
				this.addEventListener(Event.COMPLETE, completeLoadLocallyHandler);
			}
			else
			{
				this.addEventListener(Event.COMPLETE, completeLoadLocallyHandlerBytes);
			}
			this.browse([fileFilter]);
		}
		
		private function fileSelectedLocallyHandler(e:Event):void
		{
			this.load();
		}
		
		private function completeLoadLocallyHandlerBytes(e:Event):void
		{
			var a:ByteArray = this.data;
			callBack(a);
		}
		
		private function completeLoadLocallyHandler(e:Event):void
		{
			var a:ByteArray = this.data;
			var l:Loader = new Loader();
			l.contentLoaderInfo.addEventListener(Event.COMPLETE, function (e:Event):void{
				var bmd:BitmapData = new BitmapData(l.width, l.height, true, 0xFFFFFF);
				bmd.draw(l);
				callBack(new Bitmap(bmd));
			});
			l.loadBytes(a);
		}
		
		private function ioErrorHandler(e:IOErrorEvent):void
		{
			Alert.show(IOERROR_MSG);
		}
		private function securityErrorHandler(e:SecurityErrorEvent):void
		{
			Alert.show(SECURITY_ERROR_MSG);
		}
		
		public function saveFile(dataObj:Object, fileName:String="fileName"):void
		{
			this.save(dataObj, fileName);
		}		
		
		
	}
}